package net.guerlab.smart.wx.internal.controller.inside;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.error.WxErrorException;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.wx.core.domain.LoginResponse;
import net.guerlab.smart.wx.core.domain.MaEncryptedData;
import net.guerlab.smart.wx.service.service.WxMaLoginService;
import net.guerlab.smart.wx.service.service.WxMaManagerService;
import net.guerlab.web.result.Result;
import net.guerlab.web.result.Succeed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * 小程序
 *
 * @author guer
 */
@Api(tags = "小程序")
@RestController("/inside/wx/ma")
@RequestMapping("/inside/wx/ma")
@Transactional(rollbackFor = Exception.class)
public class WxMaController {

    private WxMaLoginService loginService;

    private WxMaManagerService managerService;

    @ApiOperation("登录")
    @GetMapping("/{appId}/login/{code}")
    public LoginResponse login(@ApiParam(value = "应用ID", required = true) @PathVariable String appId,
            @ApiParam(value = "code", required = true) @PathVariable String code) {
        return loginService.login(appId, code, "inside", "inside");
    }

    @ApiOperation("注册")
    @PostMapping("/{appId}/register/{openId}")
    public LoginResponse register(@ApiParam(value = "应用ID", required = true) @PathVariable String appId,
            @ApiParam(value = "openId", required = true) @PathVariable String openId,
            @RequestBody MaEncryptedData encryptedData) {
        return loginService.register(appId, openId, encryptedData);
    }

    @ApiOperation("获取accessToken")
    @GetMapping("/{appId}/accessToken")
    public Result<String> getAccessToken(@ApiParam(value = "应用ID", required = true) @PathVariable String appId) {
        try {
            return new Succeed<>(Succeed.MSG, managerService.getService(appId).getAccessToken());
        } catch (WxErrorException e) {
            throw new ApplicationException(e.getError().getErrorMsg(), e.getError().getErrorCode());
        }
    }

    @Autowired
    public void setLoginService(WxMaLoginService loginService) {
        this.loginService = loginService;
    }

    @Autowired
    public void setManagerService(WxMaManagerService wxMaManagerService) {
        this.managerService = wxMaManagerService;
    }
}
